import React, { useEffect, useRef, useState } from 'react';
import './modal.scss';
import { CloseIcon } from '../icon/icon';
import HSUIButton from '../button/button';
import ReactDOM from 'react-dom';

export interface ModalProps {
	open: boolean;
	title?: string;
	header?: React.ReactNode;
	closeIcon?: React.ReactNode;
	footer?: React.ReactNode;
	children?: React.ReactNode;
	canceltext?: string;
	okText?: string;
	isShowOkBtn?: boolean;
	isShowCancelBtn?: boolean;
	maskClosable?: boolean;
	isShowCloseIcon?: boolean;
	closeByESC?: boolean;
	appendToBody?: boolean;
	destroyOnClose?: boolean;
	onOk?: (...args: any[]) => any;
	onCancel?: (...args: any[]) => any;
	onClose?: (...args: any[]) => any;
}

const DefaultModal = (props: ModalProps) => {
	const {
		open,
		title = 'modal title',
		header,
		closeIcon,
		footer,
		children,
		canceltext = '取消',
		okText = '确认',
		isShowOkBtn = true,
		isShowCancelBtn = true,
		maskClosable = false,
		isShowCloseIcon = true,
		closeByESC = false,
		onOk,
		onCancel,
		onClose,
	} = props;

	const maskRef = useRef<HTMLDivElement>(null);
	const hiddenModal = () => {
		maskRef.current ? (maskRef.current.style.display = 'none') : '';
	};
	const showModel = () => {
		maskRef.current ? (maskRef.current.style.display = 'flex') : '';
	};
	const closeModal = (e: React.MouseEvent<HTMLDivElement>) => {
		hiddenModal();
		if (onCancel) {
			onCancel(e);
		}
	};
	const clickESC = (e: KeyboardEvent) => {
		if (e.key === 'Escape') {
			maskRef.current?.click();
		}
	};

	useEffect(() => {
		if (open) {
			showModel();
		} else {
			hiddenModal();
		}

		if (closeByESC) {
			window.addEventListener('keydown', clickESC);
		}

		return () => {
			if (closeByESC) {
				window.removeEventListener('keydown', clickESC);
			}
		};
	}, [open]);
	return (
		<div
			ref={maskRef}
			className="hs-ui-modal-mask"
			onClick={maskClosable ? closeModal : () => {}}>
			<div
				className="hs-ui-modal"
				onClick={(e) => e.stopPropagation()}>
				<div className="hs-ui-modal-wrapper">
					<div className="hs-ui-modal__header">
						<div className="hs-ui-modal__header-title">{header ?? title}</div>
						{isShowCloseIcon && (
							<div className="hs-ui-modal__close">
								{closeIcon ?? (
									<HSUIButton onClick={onClose ?? onCancel}>
										<CloseIcon />
									</HSUIButton>
								)}
							</div>
						)}
					</div>
					<div className="hs-ui-modal__body">{children ?? <div>modal body</div>}</div>
					<div className="hs-ui-modal__footer">
						{footer ?? (
							<>
								{isShowOkBtn && (
									<HSUIButton
										type="success"
										size="medium"
										className="hs-ui-modal__footer-cancel"
										onClick={onCancel}>
										{canceltext}
									</HSUIButton>
								)}
								{isShowCancelBtn && (
									<HSUIButton
										type="success"
										size="medium"
										className="hs-ui-modal__footer-ok"
										onClick={onOk}>
										{okText}
									</HSUIButton>
								)}
							</>
						)}
					</div>
				</div>
			</div>
		</div>
	);
};

const Modal = (props: ModalProps) => {
	const { open, appendToBody = true, destroyOnClose = true } = props;
	const [newModal, setNewModal] = useState<Element | null>();

	let div: any = null;
	useEffect(() => {
		if(open) {
			if (appendToBody) {
				div = document.createElement('div');
				document.body.appendChild(div);
				setNewModal(div);
			}
		} else {
			if (destroyOnClose && div) {
				document.body.removeChild(div);
				setNewModal(null); 
			} 
		}
		return () => {
			if (div) {
				document.body.removeChild(div);
			}
		};
	}, [open]);

	return appendToBody ? (
		newModal && ReactDOM.createPortal(<DefaultModal {...props} />, newModal)
	) : (
		<DefaultModal {...props} />
	);
};

export default Modal;
